package com.bins.uaa.user.service;

import com.bins.uaa.user.api.vo.MenuVo;
import com.bins.uaa.user.api.vo.UserVo;
import com.bins.uaa.user.dao.MenuMapper;
import com.bins.uaa.user.dao.UserRepository;
import com.bins.uaa.user.model.Menu;
import com.bins.uaa.user.model.User;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    MenuMapper menuMapper;

    public User findByUsername(String userName){
        return userRepository.findByUserName(userName);
    }

    public UserVo getUserByUsername(String username){
        User user = this.findByUsername(username);
        if(user == null){
            return null;
        }
        Long userId = user.getId();
        // List<MenuVo> menus = this.getMenuList(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        // userVo.setPermissions(menus);
        return userVo;
    }

    public List<MenuVo> getMenuList(Long userId) {
        List<Menu> menus = menuMapper.selectPermissionByUserId(userId);
        if (CollectionUtils.isEmpty(menus)) {
            return Collections.emptyList();
        }
        List<MenuVo> menuList = Lists.newArrayListWithCapacity(menus.size());
        MenuVo vo;
        for (Menu menu : menus) {
            vo = new MenuVo();
            vo.setCode(menu.getCode());
            menuList.add(vo);
        }
        return menuList;
    }

    public void save(User newUser) {
        userRepository.save(newUser);
    }
}
